﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class Advance : System.Web.UI.Page
{
    DataTable dt;
   public static string conexion = ConfigurationManager.ConnectionStrings["conexion"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (!IsPostBack)
        {
            CmbFechaDesde.SelectedDate = DateTime.Now;
            CmbFechaHasta.SelectedDate = DateTime.Now;
            string QueryTargets = "SELECT Target FROM Tolerancias";
            string QueryLineas = "SELECT Codigo, Linea + ' ' + Tubo as Lineatubo FROM OPTIMAS WHERE empaque=1 order by linea";

            SqlDataAdapter da = new SqlDataAdapter(QueryLineas, conexion);
            DataTable dt = new DataTable();
            da.Fill(dt);
            CheckBoxList1.DataSource = dt;
            CheckBoxList1.DataTextField = "Lineatubo";
            CheckBoxList1.DataValueField = "Codigo";

            dt = new DataTable();
            da = new SqlDataAdapter(QueryTargets, conexion);
            da.Fill(dt);
            RadComboBox1.DataSource = dt;
            RadComboBox1.DataTextField = "Target";
            RadComboBox1.DataValueField = "Target";

            DataBind();


        }
        else
        {
            dt = (DataTable)Session["DatasCompletos"];
           RadGrid1.DataSource=dt;
            DataBind();
        
        }
    
        
    }
   //Se obtienen los valores seleccionados en los checkboxes
  
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {

        
        string Valores = "";
        for (int i = 0; i < CheckBoxList1.Items.Count; i++)
        {
            if ( CheckBoxList1.Items[i].Selected)
            {
                Valores += CheckBoxList1.Items[i].Value + ",";
                
            }
        }
        if (Valores == "")
        {
           
                LbMensaje.Text = "¡You have not selected a line!";
            
        }
        else
        {
            LbMensaje.Text = "";
        string Codigos = Valores.Substring(0, Valores.Length - 1);

        string QueryReport = "EXEC Report_All_Lines '" + Codigos + "', '" + CmbFechaDesde.SelectedDate + "','" + CmbFechaHasta.SelectedDate + "','"+RadComboBox1.SelectedValue+"'";
        Response.Write(QueryReport);
        dt = new DataTable();
        
        SqlDataAdapter da = new SqlDataAdapter(QueryReport, conexion);

        da.Fill(dt);
        RadGrid1.DataSource = dt;
        DataBind();
        Session["DatasCompletos"] = dt;
        if (dt.Rows.Count > 0)
        {
            //Se genera y asigna la variable que contiene el total de bolsa producidas:
            string contador = dt.Rows.Count.ToString();
            LbTotal.Text = contador;


            //Desviacion standart:

            List<double> Datos = new List<double>();

            for (int i = 0; i < dt.Rows.Count; i++)
            {

                Datos.Add(Convert.ToDouble(dt.Rows[i]["peso"]));
            }

            Double promedio = Datos.Average();
            double promedioRound = Math.Round(promedio, 2);
            LbPromedio.Text = promedioRound.ToString();

            Double sumas = Datos.Select(val => Math.Pow(val - promedio, 2)).Sum();
            Double Desviacion = Math.Sqrt(sumas / (Datos.Count - 1));
            double DesviacionRound = Math.Round(Desviacion, 2);

            LbDesv.Text = DesviacionRound.ToString();


            //Target
            DataRow row = dt.Rows[0];
            string target;
            target = Convert.ToString(row["Target"]);
            LbTarget.Text = target;

            //Op   
            Double op;

            op = promedio - Convert.ToDouble(target) / Convert.ToDouble(target);
            double opRound = Math.Round(op, 2);
            LbOp.Text = opRound.ToString();

            //TZ
            decimal Tz;
            Tz = Convert.ToDecimal(promedio) - Convert.ToDecimal(target) / Convert.ToDecimal(Desviacion);
            decimal TzRound = Math.Round(Tz, 2);
            LbTz.Text = TzRound.ToString();

            // % Packing
            decimal OnPacking;
            OnPacking = (Convert.ToDecimal(promedio) - Convert.ToDecimal(target)) / (Convert.ToDecimal(target)) * 100;
            decimal OnPackingRound = Math.Round(OnPacking, 2);

            LbOnPacking.Text = OnPackingRound.ToString();
            if (Convert.ToDouble(OnPackingRound) > 0.5)
            {
                Image1.ImageUrl = "images/No.JPG";
            }
            else
            {
                Image1.ImageUrl = "images/Yes.JPG";
            }



            //Se buscan los valores menores a 1000
            double tolerancia = Tolerancia(Convert.ToDouble(dt.Rows[0]["Target"].ToString()));
            List<Double> Menores = new List<double>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Convert.ToDouble(dt.Rows[i]["peso"]) < tolerancia)
                {
                    Menores.Add(Convert.ToDouble(dt.Rows[i]["peso"]));

                }

            }
            //CR

            double Cr;
            double CrRound;
            Cr = (3 * Desviacion) / (Convert.ToDouble(target) - Convert.ToDouble(tolerancia));
            CrRound = Math.Round(Cr, 2);
            LblCr.Text = CrRound.ToString();
            //Asignacion de Tolerancia al label
            LblTolerancia.Text = tolerancia.ToString();

            double NumTolerancias;
            NumTolerancias = Menores.Count;
            
            LblNumTolerancia.Text = NumTolerancias.ToString();
            //foreach (double txt in Menores)
            //{
            //    Response.Write(txt + "<br>");
            //}

        }



    }
    }
    public static double Tolerancia(double dlb)
    {
        DataTable dt = new DataTable();
        string queryTolerancia = "SELECT * FROM Tolerancias where Target=" + dlb;
        SqlDataAdapter da = new SqlDataAdapter(queryTolerancia, conexion);
        da.Fill(dt);
        return Convert.ToDouble(dt.Rows[0]["Tolerancia"].ToString());

    }



    protected void Button1_Click(object sender, EventArgs e)
    {
        RadGrid1.ExportSettings.IgnorePaging = true;
        RadGrid1.ExportSettings.OpenInNewWindow = true;
        RadGrid1.MasterTableView.ExportToExcel();
    }
}

